package com.example.demo.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-08-11
 * Time:16:56
 */

@ControllerAdvice
@ResponseBody// 表示当前的所有方法返回的都是数据不是页面
public class ExHandler {

    /**
     * 拦截所有的空指针异常，继续统一的数据返回
     */

    @ExceptionHandler(NullPointerException.class)// 空指针异常
    public HashMap<String,Object> nullException(NullPointerException e){
        HashMap<String,Object> result = new HashMap<>();
        result.put("code","-1");
        result.put("msg","空指针异常:" + e.getMessage());//错误码的描述信息
        result.put("date",null);
        return result;
    }

    @ExceptionHandler(Exception.class)// 所有异常
    public HashMap<String,Object> AllException(Exception e){
        HashMap<String,Object> result = new HashMap<>();
        result.put("code","-1");
        result.put("msg","异常:" + e.getMessage());//错误码的描述信息
        result.put("date",null);
        return result;
    }
}
